﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.CM
{
    public partial class ContractAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {
                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取合同信息
        /// </summary>
        public void GetContractList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startSignDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startSignDate").FirstOrDefault().Field = "SignDate";
                }
                if (listSearch.Where(s => s.Field == "endSignDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endSignDate").FirstOrDefault().Field = "SignDate";
                }
            }
            Expression<Func<View_CM_Contract, bool>> exp = SearchExpression.FindByGroup<View_CM_Contract>(listSearch);
            string OrderId = OperateContext.Sort == null ? "FillDate" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_CM_ContractDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, false);
            count = DALSession.Current.View_CM_ContractDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        /// <summary>
        /// 通过ID获取合同信息
        /// </summary>
        public void GetContractByID()
        {
            if (Request["id"] != null)
            {
                int code = Commons.String2Int32(Request["id"]);
                var list = DALSession.Current.View_CM_ContractDAL.GetListBy(c => c.ID == code).FirstOrDefault();
                Response.Write(JsonHelper.toJson(list));
            }
            //根据报价单ID获取相关信息
            if (Request["quotID"] != null)
            {
                int quotID = Commons.String2Int32(Request["quotID"]);
                var list = DALSession.Current.View_CM_QuotationDAL.GetListBy(c => c.ID == quotID).FirstOrDefault();
                if (list == null) return;
                View_CM_Contract pernew = new View_CM_Contract();
                pernew.SignDate = DateTime.Now.ToString("yyyy-MM-dd");
                //pernew.CustomerName = list.CustomerName;
                //pernew.SupplierName = list.SupplierName;
                pernew.FillPerson = OperateContext.SessBasicInfo.UserInfo.Name.ToString();
                pernew.FillDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                Response.Write(JsonHelper.toJson(pernew));
            }
        }

        /// <summary>
        /// 修改合同信息
        /// </summary>
        public void EditContract()
        {
            int ID = Commons.String2Int32(Request.Form["ID"]);
            CM_Contract perNew = DALSession.Current.CM_ContractDAL.GetListBy(d => d.ID == ID).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, perNew);
            DALSession.Current.CM_ContractDAL.ModifyAllModel(perNew);
            DALSession.Current.CM_ContractDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }

        /// <summary>
        /// 添加合同信息
        /// </summary>
        public void AddContract()
        {

            CM_Contract per = new CM_Contract();
            ModelTools.Form2EditModel(Request.Form, per);
            per.FillDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //默认合同未完结、未开票
            per.IsComplete = "0";
            per.IsInvoice = "0";
            //生成流水号 HTyyMMdd0002
            string newId = "HT";
            string time = DateTime.Now.ToString("yyMMdd");
            var con = DALSession.Current.CM_ContractDAL.GetListBy(c => c.Code.Substring(2, 6) == time, p => p.Code, false).FirstOrDefault();
            if (con == null)
            {
                newId += time + "0001";
            }
            else
            {
                newId += time + (Commons.String2Int32(con.Code.Substring(8, 4)) + 1).ToString().PadLeft(4, '0');
            }
            per.Code = newId;

            int[] quotID;
            if (Request.Form["quotID"].Contains("["))
            {
                //多个报价单
                quotID = JsonConvert.DeserializeObject<int[]>(Request.Form["quotID"]);
            }
            else
            {
                //只选了一个报价单
                quotID = new int[1];
                quotID[0] = JsonConvert.DeserializeObject<int>(Request.Form["quotID"]);
            }
            decimal money = 0;
            foreach (var id in quotID)
            {
                //计算合同总金额
                var list = DALSession.Current.CM_QuotationDetailDAL.GetListBy(qd => qd.QuotationID == id);
                money += (decimal)list.Sum(pd => pd.TotalPrice);

                //将供应商ID、客户ID带到合同
                CM_Quotation perQuot = DALSession.Current.CM_QuotationDAL.GetListBy(d => d.ID == id).FirstOrDefault();
                per.SupplierID = perQuot.SupplierID;
                per.CustomerID = perQuot.CustomerID;
            }
            per.ContractMoney = money;
            //添加合同
            int retID = Convert.ToInt32(DALSession.Current.CM_ContractDAL.AddModelReturnId(per, "ID"));
            DALSession.Current.CM_ContractDAL.SaveChanges();
            //更新报价单、合同状态
            foreach (var id in quotID)
            {
                //更新报价单的合同ID、合同号、报价单状态
                CM_Quotation perQuot = DALSession.Current.CM_QuotationDAL.GetListBy(d => d.ID == id).FirstOrDefault();
                if (perQuot.State == "0") perQuot.State = "1"; //如果是报价单状态，则更新为已合同
                else if (perQuot.State == "2") perQuot.State = "3"; //如果是已订单状态，则更新为已合同已订单
                perQuot.ContractID = retID;
                perQuot.ContractCode = per.Code;
                DALSession.Current.CM_QuotationDAL.ModifyAllModel(perQuot);
                //同步更新生产订单的状态以及生产订单绑定的合同号
                PM_ProductOrder perProd = DALSession.Current.PM_ProductOrderDAL.GetListBy(d => d.QuotationID == id).FirstOrDefault();
                if (perProd != null)
                {
                    perProd.State = perQuot.State;
                    perProd.ContractID = retID;
                    perProd.ContractCode = per.Code;
                    DALSession.Current.PM_ProductOrderDAL.ModifyBy(perProd, p => p.ID == perProd.ID, "State", "ContractID", "ContractCode");

                    //同步更新发货单绑定的合同号
                    CM_Delivery perDeli = DALSession.Current.CM_DeliveryDAL.GetListBy(d => d.ProductOrderID == perProd.ID).FirstOrDefault();
                    if (perDeli != null)
                    {
                        perDeli.ContractID = retID;
                        perDeli.ContractCode = per.Code;
                        DALSession.Current.CM_DeliveryDAL.ModifyBy(perDeli, p => p.ProductOrderID == perProd.ID, "ContractID", "ContractCode");
                    }
                }
            }
            DALSession.Current.CM_DeliveryDAL.SaveChanges();
            DALSession.Current.PM_ProductOrderDAL.SaveChanges();
            DALSession.Current.CM_QuotationDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }

        /// <summary>
        /// 删除合同信息
        /// </summary>
        public void DelContract()
        {
            if (Request.Form["ID"] == null)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "删除失败"));
                return;
            }
            int Id = Convert.ToInt32(Request.Form["ID"].ToString());
            DALSession.Current.CM_ContractDAL.DelBy(p => p.ID == Id);
            DALSession.Current.CM_ContractDAL.SaveChanges();
            //更新报价单状态，取消报价单中绑定的合同
            var quotList = DALSession.Current.CM_QuotationDAL.GetListBy(d => d.ContractID == Id).ToList();
            quotList.ForEach(q =>
            {
                q.ContractID = null;
                q.ContractCode = null;
                if (q.State == "1") q.State = "0"; //如果是已合同状态，则更新为已合同
                else if (q.State == "3") q.State = "2"; //如果是已合同已订单状态，则更新为已订单
                DALSession.Current.CM_QuotationDAL.ModifyAllModel(q);

                //同步更新生产订单的状态并取消生产订单绑定的合同号
                PM_ProductOrder perProd = DALSession.Current.PM_ProductOrderDAL.GetListBy(d => d.QuotationID == q.ID).FirstOrDefault();
                if (perProd != null)
                {
                    perProd.State = q.State;
                    perProd.ContractID = null;
                    perProd.ContractCode = null;
                    DALSession.Current.PM_ProductOrderDAL.ModifyBy(perProd, p => p.ID == perProd.ID, "State", "ContractID", "ContractCode");
                    //同步更新发货单绑定的合同号
                    CM_Delivery perDeli = DALSession.Current.CM_DeliveryDAL.GetListBy(d => d.ProductOrderID == perProd.ID).FirstOrDefault();
                    if (perDeli != null)
                    {
                        perDeli.ContractID = null;
                        perDeli.ContractCode = null;
                        DALSession.Current.CM_DeliveryDAL.ModifyBy(perDeli, p => p.ProductOrderID == perProd.ID, "ContractID", "ContractCode");
                    }
                }
            });
            DALSession.Current.CM_DeliveryDAL.SaveChanges();
            DALSession.Current.CM_QuotationDAL.SaveChanges();
            DALSession.Current.PM_ProductOrderDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }

        /// <summary>
        /// 获取所有合同的信息列表
        /// </summary>
        public void GetAllContract()
        {
            string q = Request.Form["q"];
            if (q == null)
            {
                var list = DALSession.Current.CM_ContractDAL.GetListBy(r=>r.IsComplete=="1",r=>r.ID,false);
                Response.Write(JsonHelper.toPageJson(list, list.Count()));
            }
            else
            {
                var list = DALSession.Current.CM_ContractDAL.GetListBy(r => r.IsComplete == "1" && r.Code.Contains(q), r => r.ID, false);
                Response.Write(JsonHelper.toPageJson(list, list.Count()));
            }
            //Response.Write(JsonHelper.toJson(DALSession.Current.CM_ContractDAL.GetListBy(c => c.IsComplete=="1")));
        }

        /// <summary>
        /// 完结合同
        /// </summary>
        public void DoneContract()
        {
            if (Request.Form["ID"] != null)
            {
                int Id = Convert.ToInt32(Request.Form["ID"].ToString());
                var perCont = DALSession.Current.CM_ContractDAL.GetListBy(d => d.ID == Id).FirstOrDefault();
                perCont.IsComplete = "1";
                perCont.CompleteDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                DALSession.Current.CM_ContractDAL.ModifyBy(perCont, p => p.ID == Id, "IsComplete", "CompleteDate");
                DALSession.Current.CM_ContractDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true, "操作成功"));
            }
        }

        /// <summary>
        /// 通过合同ID获取合同及客户相关信息，用于打印
        /// </summary>
        public void GetContractAndCustomerInfoByID() {
            if (Request["id"] != null) {
                int code = Commons.String2Int32(Request["id"]);
                var list = DALSession.Current.View_CM_ContractAndCustomerDAL.GetListBy(c => c.ID == code).FirstOrDefault();
                Response.Write(JsonHelper.toJson(list));
            }
        }
    }
}